<?php
namespace App\Utils\WechatSdk;

/*
*
* Implement interface of wechat to communicate with wechat.
*
* (c) hjiash <hjs@zerioi.com>
*
*/

class MySimpleXMLElement extends \SimpleXMLElement{

    public function addCDataChild($name , $value) {
        $new = parent::addChild($name);
        $base = dom_import_simplexml($new);
        $docOwner = $base->ownerDocument;
        $base->appendChild($docOwner->createCDATASection($value));
    }

}

class XmlOperator {
	/**
	 * [parseXml 解析xml，转化为数组存储]
	 * @param  string $data   [需严格遵从xml的定义和格式]
	 * @param  array  $result [存储当前解析对应的数组，递归操作时用；默认为null]
	 * @return array          [返回解析后的数组，子节点按多维数组的方式获取]
	 */
	public static function parseXml($data, $result=null){
		if ($result == null) {
			$result = array();
		}

		$xml = new \SimpleXMLIterator($data);
		foreach ($xml as $key => $value) {
			if (is_array($value)) {
				$result[$key] = self::parseXml($value);
			}else {
				$result[$key] = (string)$value;
			}
		}

		return $result;
	}


	/**
	 * [genXML 将数组转化为xml字符串，根节点默认为<xml/>]
	 * @param  array  $data         [需要转化为xml的数组]
	 * @param  string $rootNodeName [根节点名称，默认为<xml/>]
	 * @param  string $xml          [存储当前生成的xml字符串，多维数组递归操作时用；默认为null]
	 * @return string               [返回转化成功后的xml字符串]
	 */
	public static function genXML($data, $rootNodeName = 'xml', $xml = null){
		if ($xml == null) {
			$xml = new MySimpleXMLElement('<xml/>');
		}
		
		foreach ($data as $key => $value) {
			if (is_array($value)) {
				$node = $xml->addChild($key);
				self::genXML($value, $rootNodeName, $node);
			}else {
				$xml->addCDataChild($key, $value);
			}
		}

		return $xml->asXML();
	}
}
?>
